package com.example.blue_plugin;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.RequiresApi;
import com.example.blue_plugin.callback.ConnectStateCallback;
import com.example.blue_plugin.callback.DeviceSignalCallback;
import com.example.blue_plugin.callback.DiscoverServiceCallback;
import com.example.blue_plugin.callback.MtuChangeCallback;
import com.example.blue_plugin.callback.RssiChangeCallback;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


//封装的蓝牙设备对象
public class Device {
    private short connectState = 0;//当前设备的状态,0代表未连接,1代表正在连接,2代表已连接
    private int curRssi = 0;//储存当前设备的rssi值
    private boolean isWatchRssi = false;//是否要监听rssi
    private BluetoothGatt mBleGatt;//蓝牙连接对象
    private Context mContext;//当前应用的上下文
    private final String BLUETOOTH_NOTIFY_D = "00002902-0000-1000-8000-00805f9b34fb";//此属性是用来开启通知的时获取notify特征值的描述对象,默认是这个描述uuid
    private final String BLUETOOTH_UUID_XUEYA = "00002a35-0000-1000-8000-00805f9b34fb";//血压的这个属性比较特殊
    private BluetoothDevice bleDevice;//蓝牙设备对象
    private BleGattCallback mGattCallback = new BleGattCallback();
    private Handler mHandler;//为了开启定时任务
    private boolean isConnectedDevice = false;//判断是否曾经连接上设备
    private boolean isInitiativeDisConnect = false;//判断是否是手动断开连接
    private short connectRetryTimes = 0;//连接重试次数
    private ConnectStateCallback connectStateCallback;//连接状态的回调
    private DeviceSignalCallback deviceSignalCallback;//设备传回数据时的回调
    private DiscoverServiceCallback discoverServiceCallback;//发现蓝牙服务之后的回调
    private MtuChangeCallback mtuChangeCallback;//mtu被修改之后的回调
    private RssiChangeCallback rssiChangeCallback;//rssi修改之后的回调
    private Runnable connectTimeoutCallback = () -> {//连接超时的回调
        if (mBleGatt != null) {
            mBleGatt.close();//直接将连接资源关闭，这样连接回调也不会被调用
            mBleGatt = null;
            connectState = 0;
        }
        connectStateCallback.connectTimeout(bleDevice.getAddress());//连接超时的回调
    };

    private Handler handler = new Handler();
    private List<String> uuidList = new ArrayList<>();//特征值的list
    private String serviceid = "";//指定服务uuid

    public Device(Context mContext, Handler handler, BluetoothDevice bleDevice, ConnectStateCallback connectStateCallback, DeviceSignalCallback deviceSignalCallback, DiscoverServiceCallback discoverServiceCallback, MtuChangeCallback mtuChangeCallback, RssiChangeCallback rssiChangeCallback, int rssi) {
        this.mContext = mContext;
        this.mHandler = handler;
        this.bleDevice = bleDevice;
        this.connectStateCallback = connectStateCallback;
        this.discoverServiceCallback = discoverServiceCallback;
        this.deviceSignalCallback = deviceSignalCallback;
        this.mtuChangeCallback = mtuChangeCallback;
        this.rssiChangeCallback = rssiChangeCallback;
        this.curRssi = rssi;
    }

    public Device(Context mContext, Handler handler, BluetoothDevice bleDevice, ConnectStateCallback connectStateCallback, DeviceSignalCallback deviceSignalCallback, DiscoverServiceCallback discoverServiceCallback, MtuChangeCallback mtuChangeCallback, RssiChangeCallback rssiChangeCallback, int rssi, List<String> uuidList, String serviceid) {
        this.mContext = mContext;
        this.mHandler = handler;
        this.bleDevice = bleDevice;
        this.connectStateCallback = connectStateCallback;
        this.discoverServiceCallback = discoverServiceCallback;
        this.deviceSignalCallback = deviceSignalCallback;
        this.mtuChangeCallback = mtuChangeCallback;
        this.rssiChangeCallback = rssiChangeCallback;
        this.curRssi = rssi;
        this.uuidList = uuidList;
        this.serviceid = serviceid;
    }

    /**
     * 销毁对象
     */
    public void destroy() {
        mHandler.removeCallbacks(connectTimeoutCallback);//停止连接超时的定时
        if (connectState == 2) {//如果是已经连接才能去断开连接
            isInitiativeDisConnect = true;//标记当前是手动断开的
            mBleGatt.disconnect();//断开连接
        } else {//如果未连接就直接将连接资源关闭
            if (mBleGatt != null) {
                mBleGatt.close();//直接将连接资源关闭，这样连接回调也不会被调用
                mBleGatt = null;
                connectState = 0;
            }
        }
    }

    /**
     * 更新设备对象
     */
    public void updateBleDevice(BluetoothDevice newBleDevice) {
        this.bleDevice = newBleDevice;
    }

    /**
     * 判断设备对象是否有被蓝牙堆栈缓存
     */
    public boolean isInBleCache() {
        return !(bleDevice.getType() == BluetoothDevice.DEVICE_TYPE_UNKNOWN);
    }

    /**
     * 连接设备
     */
   
    public void connectDevice(int connectTimeOut) {
        Log.i("stf", "--connectState-->" + connectState);
        if (connectState == 0) {//如果当前是未连接的状态
            connectRetryTimes = 0;
            connectState = 1;
            isConnectedDevice = false;//设置当前还未连接上过设备
            isInitiativeDisConnect = false;//设置如果断开连接不是手动断开的连接
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                mBleGatt = bleDevice.connectGatt(mContext, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
            else
                mBleGatt = bleDevice.connectGatt(mContext, false, mGattCallback);
            if (connectTimeOut > 0)
                mHandler.postDelayed(connectTimeoutCallback, connectTimeOut);//设置到达最大连接时间之后的回调
        }
    }

    /**
     * 主动与设备断开连接
     */
   
    public void initiativeDisConnect() {
        if (connectState == 2) {//如果是已经连接才能去断开连接
            isInitiativeDisConnect = true;//标记当前是手动断开的
            mBleGatt.disconnect();//断开连接
        }
    }

    /**
     * 发现服务
     */
   
    public void discoverService() {
        mBleGatt.discoverServices();//去发现服务
    }

    /**
     * 开启或关闭notify特征值
     */
   
    public boolean setNotifyCharacteristic(String serviceUuid, String characteristicUuid, boolean isEnable) {
        BluetoothGattCharacteristic notifyCharacteristic = getBluetoothGattCharacteristic(serviceUuid, characteristicUuid);
        if (mBleGatt == null || notifyCharacteristic == null)
            return false;
        if (!mBleGatt.setCharacteristicNotification(notifyCharacteristic, isEnable))//开启这个notify特征值的通知功能，其实执行这一步之后就可以获得设备传来的数据了，这步不成功，也不会发送数据
            return false;
        BluetoothGattDescriptor clientConfig = notifyCharacteristic.getDescriptor(UUID.fromString(BLUETOOTH_NOTIFY_D));
        if (clientConfig == null)
            return false;
        if (isEnable) {
            clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        } else {
            clientConfig.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        }
        boolean b = mBleGatt.writeDescriptor(clientConfig);
        return b;
    }

   
    public boolean setIndicationCharacteristic(String serviceUuid, String characteristicUuid, boolean isEnable) {
        BluetoothGattCharacteristic notifyCharacteristic = getBluetoothGattCharacteristic(serviceUuid, characteristicUuid);
        if (mBleGatt == null || notifyCharacteristic == null)
            return false;
        BluetoothGattDescriptor clientConfig = notifyCharacteristic.getDescriptor(UUID.fromString(BLUETOOTH_NOTIFY_D));
        if (clientConfig == null)
            return false;
        clientConfig.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        boolean b = mBleGatt.writeDescriptor(clientConfig);
        startSend(serviceUuid,characteristicUuid);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startRead(serviceUuid,characteristicUuid);
            }
        },200);
        return b;
    }

   
    public void startSend(String serviceUuid, String characteristicUuid) {
        if (mBleGatt != null) {
            BluetoothGattService gattService = mBleGatt.getService(UUID.fromString(serviceUuid));
            if (gattService != null) {
                BluetoothGattCharacteristic characteristic = gattService.getCharacteristic(UUID.fromString(characteristicUuid));
                if (characteristic != null) {
                    String order = "7B A5 000000000101  C60400000000 0000B75A";
                    byte[] send_data = hex2Bytes(order);
                    send_data[14] = 70;
                    send_data[15] = 34;
                    characteristic.setValue(send_data);
                    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
                    boolean b = mBleGatt.writeCharacteristic(characteristic);
                    Log.d("stf", "startSend: " + b);
                }
            }
        }

    }

   
    public void startRead(String serviceUuid, String characteristicUuid) {
        if (mBleGatt != null ) {
            BluetoothGattService gattService = mBleGatt.getService(UUID.fromString(serviceUuid));
            BluetoothGattCharacteristic characteristic = gattService.getCharacteristic(UUID.fromString(characteristicUuid));
            boolean b = mBleGatt.setCharacteristicNotification(characteristic, true);
            if (b) {

                List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
                for (BluetoothGattDescriptor descriptor : descriptors) {

                    boolean b1 = descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                    if (b1) {
                        mBleGatt.writeDescriptor(descriptor);
                        Log.d("stf", "startRead: " + "监听收数据");
                    }
                }
            }
        }
    }

    /**
     * hex字符串转byte数组<br/>
     * 2个hex转为一个byte
     *
     * @param src
     * @return
     */

    public static byte[] hex2Bytes(String src) {
        src = src.replaceAll(" ", "");
        if (src.length() % 2 != 0) {
            return null;
        }
        byte[] res = new byte[src.length() / 2];
        char[] chs = src.toCharArray();
        for (int i = 0, c = 0; i < chs.length; i += 2, c++) {
            res[c] = (byte) (Integer.parseInt(new String(chs, i, 2), 16));
        }
        return res;
    }

    /**
     * 将字节 转换为字符串
     *
     * @param src 需要转换的字节数组
     * @return 返回转换完之后的数据
     */

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();

    }

    /**
     * 将字符串转化为16进制的字节
     *
     * @param message 需要被转换的字符
     * @return
     */
    public static byte[] getHexBytes(String message) {
        int len = message.length() / 2;
        char[] chars = message.toCharArray();
        String[] hexStr = new String[len];
        byte[] bytes = new byte[len];
        for (int i = 0, j = 0; j < len; i += 2, j++) {
            hexStr[j] = "" + chars[i] + chars[i + 1];
            bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
        }
        return bytes;
    }

    /**
     * 使用读特征值向设备读取数据
     */
    public void readDataToDevice(String serviceUuid, String characteristicUuid) {
        BluetoothGattCharacteristic mBleGattCharacteristic = getBluetoothGattCharacteristic(serviceUuid, characteristicUuid);
        if (mBleGattCharacteristic != null) {
            UUID uuid = mBleGattCharacteristic.getUuid();
            int properties = mBleGattCharacteristic.getProperties();
            Log.i("stf", "-读取数据申请readDataToDevice-uuid->" + uuid + "--properties->" + properties);
            boolean b = mBleGatt.readCharacteristic(mBleGattCharacteristic);//读取
            Log.i("stf", "-readDataToDevice-b-->" + b);
        }
    }

    /**
     * 使用写特征值向设备发送数据
     */
    public void writeDataToDevice(String serviceUuid, String characteristicUuid, boolean isNoResponse, byte[] data) {
        BluetoothGattCharacteristic mBleGattCharacteristic = getBluetoothGattCharacteristic(serviceUuid, characteristicUuid);
        if (mBleGattCharacteristic != null) {
            mBleGattCharacteristic.setValue(data);
            mBleGattCharacteristic.setWriteType(isNoResponse ? BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE : BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);//是否是有响应写
            mBleGatt.writeCharacteristic(mBleGattCharacteristic); //发送
        }
    }

    /**
     * 使用特征值的描述向设备读取数据
     */
    public void readDescriptorDataToDevice(String serviceUuid, String characteristicUuid, String descriptorUuid) {
        BluetoothGattDescriptor mBleGattDescriptor = getBluetoothGattDescriptor(serviceUuid, characteristicUuid, descriptorUuid);
        if (mBleGattDescriptor != null)
            mBleGatt.readDescriptor(mBleGattDescriptor);//读取
    }

    /**
     * 使用特征值的描述向设备写数据
     */
    public void writeDescriptorDataToDevice(String serviceUuid, String characteristicUuid, String descriptorUuid, byte[] data) {
        BluetoothGattDescriptor mBleGattDescriptor = getBluetoothGattDescriptor(serviceUuid, characteristicUuid, descriptorUuid);
        if (mBleGattDescriptor != null) {
            mBleGattDescriptor.setValue(data);
            mBleGatt.writeDescriptor(mBleGattDescriptor);//写入
        }
    }

    /**
     * 修改mtu,需要android版本大于21
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public boolean requestMtu(int newMtu) {
        return mBleGatt.requestMtu(newMtu);
    }

    /**
     * 开启对该设备rssi变化的轮询监听
     */
    public boolean watchRssi(boolean isStart) {
        isWatchRssi = isStart;
        if (isStart) {
            if (connectState == 2 && mBleGatt != null) {
                mBleGatt.readRemoteRssi();
                return true;
            }
            return false;
        }
        return true;
    }

    /**
     * 根据服务UUID和特征UUID和描述UUID,获取一个描述{@link BluetoothGattDescriptor}
     */
    private BluetoothGattDescriptor getBluetoothGattDescriptor(String serviceUUID, String characteristicUUID, String descriptorUUID) {
        BluetoothGattCharacteristic characteristic = getBluetoothGattCharacteristic(serviceUUID, characteristicUUID);
        if (characteristic == null)
            return null;
        return characteristic.getDescriptor(UUID.fromString(descriptorUUID));
    }

    /**
     * 根据服务UUID和特征UUID,获取一个特征{@link BluetoothGattCharacteristic}
     */
    private BluetoothGattCharacteristic getBluetoothGattCharacteristic(String serviceUUID, String characteristicUUID) {
        BluetoothGattService service = getBluetoothGattService(serviceUUID);
        if (service == null)
            return null;
        return service.getCharacteristic(UUID.fromString(characteristicUUID));
    }

    /**
     * 根据服务UUID,获取一个服务{@link BluetoothGattService}
     */
    private BluetoothGattService getBluetoothGattService(String serviceUUID) {
        return mBleGatt.getService(UUID.fromString(serviceUUID));
    }

    /**
     * 蓝牙GATT连接及操作事件回调
     */
   
    private class BleGattCallback extends BluetoothGattCallback implements Serializable {
        //连接状态改变
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.i("stf", "---onConnectionStateChange-连接状态改变-->");
            if (newState == BluetoothProfile.STATE_CONNECTED) { //连接成功
                Log.i("stf", "---连接成功-mBleGatt->" + mBleGatt);
                isConnectedDevice = true;//标志曾经连接上设备
                mHandler.removeCallbacks(connectTimeoutCallback);//停止连接超时的定时
                connectState = 2;//将状态修改为已连接
                connectStateCallback.connectSuccess(bleDevice.getAddress());//连接成功后的调用
                discoverService();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { //断开连接
                Log.i("stf", "---断开连接-->");
                if (mBleGatt != null) {
                    mBleGatt.close();
                    mBleGatt = null;
                }
                if (status == 133 && !isConnectedDevice && connectRetryTimes++ < 3) {//如果是133就要尝试去重连
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                        mBleGatt = bleDevice.connectGatt(mContext, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
                    else
                        mBleGatt = bleDevice.connectGatt(mContext, false, mGattCallback);
                } else {
                    mHandler.removeCallbacks(connectTimeoutCallback);//停止连接超时的定时
                    connectState = 0;
                    if (isConnectedDevice)//曾经连接上才叫断开,不然就是连接失败
                        connectStateCallback.disConnected(bleDevice.getAddress(), isInitiativeDisConnect);//断开连接后的调用
                }
            }
        }

        //发现新服务
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            Log.i("stf", "---onServicesDiscovered-发现新服务--mBleGatt-->" + mBleGatt + "--status-->" + status);
            if (null != mBleGatt && status == BluetoothGatt.GATT_SUCCESS) {
                List<BluetoothGattService> services = mBleGatt.getServices();
                Map<String, BluetoothGattCharacteristic> charMap = new HashMap<>();
                Map<Object, List<Map<String, Object>>> serviceMap = new HashMap<>();
                for (int i = 0; i < services.size(); i++) {//将新服务和其特征值加入Map
                    BluetoothGattService bluetoothGattService = services.get(i);
                    String serviceUuid = bluetoothGattService.getUuid().toString();
                    Log.i("stf", "---onServicesDiscovered-发现新服务--serviceUuid-->" + serviceUuid);
                    //System.out.println("发现新服务：" + serviceUuid);
                    List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
                    List<Map<String, Object>> callbackCharacteristicUuidList = new ArrayList<>(characteristics.size());//返回给flutter上层的特征值列表
                    for (int j = 0; j < characteristics.size(); j++) {
                        Map<String, Object> characteristicInfo = new HashMap<>(2);
                        BluetoothGattCharacteristic characteristic = characteristics.get(j);
                        String currentCharacteristicUuid = characteristic.getUuid().toString();

                        characteristicInfo.put("serviceUuid", serviceUuid);
                        characteristicInfo.put("uuid", currentCharacteristicUuid);
                        characteristicInfo.put("properties", characteristic.getProperties());
                        Log.i("stf", "-uuid--->" + currentCharacteristicUuid + "--特征值->" + characteristic.getProperties());
                        callbackCharacteristicUuidList.add(characteristicInfo);
                    }
                    serviceMap.put(serviceUuid, callbackCharacteristicUuidList);
                }
                discoverServiceCallback.discoverService(bleDevice.getAddress(), serviceMap);//发现蓝牙服务之后的回调
            }

            for (int i = 0; i < uuidList.size(); i++) {
                String uuid = uuidList.get(i);
                if(uuid.equals(BLUETOOTH_UUID_XUEYA)){
                    setIndicationCharacteristic(serviceid, uuid, true);
                }else {
                    setNotifyCharacteristic(serviceid, uuid, true);
                }
            }
        }

        //使用读特征值向设备读数据完成后调用的方法
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.i("stf", "根据特征值取数据-onCharacteristicRead-status->" + status + "--characteristic-->" + characteristic.getUuid().toString() + "-getValue-->" + characteristic.getValue());
            if (status == BluetoothGatt.GATT_SUCCESS) //如果读取数据成功了
                deviceSignalCallback.signalCallback((short) 0, bleDevice.getAddress(), characteristic.getUuid().toString(), true, characteristic.getValue(),bytesToHexString(characteristic.getValue()));
            else//如果失败了
                deviceSignalCallback.signalCallback((short) 0, bleDevice.getAddress(), characteristic.getUuid().toString(), false, null,null);
        }

        //使用写特征值向设备写入数据完成后调用的方法
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            Log.i("stf", "--使用写特征值向设备写入数据完成后调用的方法-onCharacteristicWrite-->" + status + "-->" + characteristic.getUuid().toString() + "--->" + characteristic.getValue());
            if(mBleGatt != null){
                mBleGatt.setCharacteristicNotification(characteristic,true);
                mBleGatt.readCharacteristic(characteristic);
            }
        }

        //通知数据
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
//            061800e2070a1d0617121ec011 血糖
//            1ec0 血糖
            Log.i("stf", "通知数据-onCharacteristicChanged-characteristic->" + characteristic.getUuid().toString() + "-getValuejson->" + characteristic.getValue()+"---->"+bytesToHexString(characteristic.getValue()));
            Log.i("stf", "通知数据-onCharacteristicChanged-characteristic->" + characteristic.getUuid().toString() + "-getValue-bytes->"+bytesToHexString(characteristic.getValue()));
            deviceSignalCallback.signalCallback((short) 2, bleDevice.getAddress(), characteristic.getUuid().toString(), true, characteristic.getValue(),bytesToHexString(characteristic.getValue()));
        }

        //读取特征值描述之后调用的函数
        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            Log.i("stf", "读取特征值描述之后调用的函数-onDescriptorRead-status->" + status + "--characteristic-->" + descriptor.getUuid().toString() + "-getValue-->" + descriptor.getValue());
            if (status == BluetoothGatt.GATT_SUCCESS) //如果读取数据成功了
                deviceSignalCallback.signalCallback((short) 3, bleDevice.getAddress(), descriptor.getUuid().toString(), true, descriptor.getValue(),bytesToHexString(descriptor.getValue()));
            else //如果失败了
                deviceSignalCallback.signalCallback((short) 3, bleDevice.getAddress(), descriptor.getUuid().toString(), false, null,null);

        }

        //写入特征值描述之后调用的函数
        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
            Log.i("stf", "写入特征值描述之后调用的函数-onDescriptorWrite-status->" + status + "--characteristic-->" + descriptor.getUuid().toString() + "-getValue-->" + descriptor.getValue());

            if (status == BluetoothGatt.GATT_SUCCESS) //如果读取数据成功了
                deviceSignalCallback.signalCallback((short) 4, bleDevice.getAddress(), descriptor.getUuid().toString(), true, descriptor.getValue(),bytesToHexString(descriptor.getValue()));
            else //如果失败了
                deviceSignalCallback.signalCallback((short) 4, bleDevice.getAddress(), descriptor.getUuid().toString(), false, null,null);
        }

        //mtu被修改后的回调
        @Override
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            if (status == BluetoothGatt.GATT_SUCCESS) //如果mtu修改成功了
                mtuChangeCallback.mtuChangeCallback(bleDevice.getAddress(), true, mtu);
            else //如果失败了
                mtuChangeCallback.mtuChangeCallback(bleDevice.getAddress(), false, mtu);
        }

        //读取设备当前信号值的回调
        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            if (isWatchRssi) {//如果当前要监听才会上报和继续获取rssi
                if (status == BluetoothGatt.GATT_SUCCESS && rssi != curRssi)//如果获取成功并且与当前值不同
                    rssiChangeCallback.rssiChangeCallback(bleDevice.getAddress(), rssi);
                if (connectState == 2 && mBleGatt != null)
                    mBleGatt.readRemoteRssi();
            }
        }
    }

}
